﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Newtonsoft.Json;
using 地图哇哇哇.地图;
using Brushes = System.Windows.Media.Brushes;
using Size = System.Windows.Size;

namespace 地图哇哇哇
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += (s, e) => { 测试啊(); };
            Closed += (s, e) => { 取消任务(); };
        }

        private Task _TaskReadText;
        private CancellationTokenSource ctsReadText = new CancellationTokenSource();
        private NotificationsManager nmApp = new NotificationsManager("提示啊", System.Drawing.Icon.ExtractAssociatedIcon(Process.GetCurrentProcess().MainModule?.FileName));

        private void ReadText(Paragraph graph, string text)
        {
            if (text == null)
                return;
            try
            {
                var ss = text.Split('\n');
                var ln = 0;
                foreach (var item in ss)
                {
                    graph.Dispatcher.InvokeAsync(() =>
                    {
                        ln++;
                        graph.Inlines.Add(new Run(ln.ToString()) {Foreground = Brushes.LightGray, Background = Brushes.Black});
                        graph.Inlines.Add(new Run(item) {Foreground = new SolidColorBrush(ColorGenerator.GetColor())});
                        graph.Inlines.Add(Environment.NewLine);
                    }, DispatcherPriority.Background);
                    //System.Threading.Thread.Sleep(50);
                    更新状态();
                }
            }
            catch
            {
                // ignored
            }
        }

        private void 更新状态()
        {
            Dispatcher.InvokeAsync(() => { run显示文本任务状态.Text = _TaskReadText.Status.ToString(); }, DispatcherPriority.Background);
        }

        private void 测试啊()
        {
            取消任务();
            try
            {
                加载随机帝国();
                var csc = Datar.生成随机测试层(new Size(canMap.ActualWidth, canMap.ActualHeight), 1, 2);
                测试层 = csc;
                当前指定区域 = csc.测试区域们.FirstOrDefault();
                刷新区域图();
                var text = JsonHelper.SerializeObject(csc, Formatting.Indented);
                run出图耗时.Text = Datar.出图耗时.ToString();
                保存文本到桌面($"地图详细配置-{Guid.NewGuid()}.json",text);
                var doc = new FlowDocument();
                var para = new Paragraph();
                doc.Blocks.Add(para);
                rtbMap.Document = doc;
                var act = new Action(() => { ReadText(para, text); });
                _TaskReadText = Task.Factory.StartNew(act, ctsReadText.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void 取消任务()
        {
            if (_TaskReadText        == null) return;
            if (_TaskReadText.Status == TaskStatus.RanToCompletion) return;
            if (ctsReadText.Token.CanBeCanceled)
            {
                ctsReadText.Cancel();
                while (ctsReadText.Token.WaitHandle.WaitOne())
                {
                }

                nmApp.ShowBalloonToolTip("提示", $"显示文本任务已取消！\n{DateTime.Now:hh:mm:ss.fff}", 500);
            }
            else
            {
                nmApp.ShowBalloonToolTip("提示", $"显示文本任务好像不能取消！\n{DateTime.Now:hh:mm:ss.fff}", icon: ToolTipIcon.Warning);
            }

            更新状态();
            nmApp.NotifyIcon.Visible = false;
            nmApp.Dispose();
        }

        public static readonly DependencyProperty 测试层属性 = DependencyProperty.Register("测试层", typeof(测试层), typeof(MainWindow), new PropertyMetadata(default(测试层)));

        public 测试层 测试层
        {
            get { return (测试层) GetValue(测试层属性); }
            set { SetValue(测试层属性, value); }
        }

        public static readonly DependencyProperty 当前指定区域属性 = DependencyProperty.Register("当前指定区域", typeof(测试区域), typeof(MainWindow), new PropertyMetadata(default(测试区域)));

        public 测试区域 当前指定区域
        {
            get { return (测试区域) GetValue(当前指定区域属性); }
            set
            {
                SetValue(当前指定区域属性, value);
                _基块啊 = 当前指定区域.基块们.Clone() as 基块[,];
            }
        }

        private void CanMap_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 2)
            {
                测试啊();
            }
        }

        private 基块[,] _基块啊 = new 基块[0, 0];

        private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
        {
            测试层 = 测试层;
            nmApp.ShowBalloonToolTip("", 测试层?.显示层格线.ToString());
            di测试层.InvalidateProperty(DrawingImage.DrawingProperty);
        }

        private void ToggleButton_OnUnchecked(object sender, RoutedEventArgs e)
        {
            测试层 = 测试层;
            nmApp.ShowBalloonToolTip("", 测试层?.显示层格线.ToString());
            di测试层.InvalidateProperty(DrawingImage.DrawingProperty);
        }

        private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            刷新区域图();
        }

        private void 刷新区域图()
        {
            if (当前指定区域 != null)
            {
                当前指定区域.陆地聚集化();
                di当前区域.Drawing = 当前指定区域.出图();
                if (测试区域.是空的二维吗(_基块啊) == false)
                {
                    当前指定区域.基块们 = _基块啊.Clone() as 基块[,];
                }
            }
        }

        private async void 加载随机帝国()
        {
            await Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { lvaaa.ItemsSource = null; }));
            var re = Task.Run(() => Datar.生成一些随机帝国(3, 7, 0, 3, 3, 5, 2, 4, 3, 6, 3, 5, 0, 2, 0, 5, 2, 5));
            await Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(async () => { lvaaa.ItemsSource = (await re).所有帝国; }));
        }

        帝国 _当前选中的帝国 = null;

        private void lvaaa_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                _当前选中的帝国 = e.AddedItems[0] as 帝国;
                tco.SelectedIndex = 1;
                rtbMap2.Dispatcher.InvokeAsync(() =>
                {
                    var json = JsonHelper.SerializeObject(_当前选中的帝国,Formatting.Indented);
                    保存文本到桌面($"选中帝国详细信息-{Guid.NewGuid()}.json",json);
                    rtbMap2.Document = new FlowDocument(new Paragraph(new Run(json)));
                }, DispatcherPriority.Background);
            }
        }

        private void 保存文本到桌面(string filename, string content)
        {
            if (cb保存文本到桌面.IsChecked.HasValue && cb保存文本到桌面.IsChecked.Value)
            {
                File.WriteAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), filename), content);
            }
        }
    }
}